﻿package game 
{
	import fl.controls.Button;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.text.TextField;
	import game.exchangeddata.ChannelInfo;
	import game.exchangeddata.UserInfo;
	import game.popups.MessagePopup;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.display.Loader;
	import game.events.EventData;
	import flash.display.*;
	import flash.text.*;
	import common.Utility;
	import flash.utils.setTimeout;
	import flash.utils.clearTimeout;
	import flash.external.ExternalInterface;
	import fl.controls.CheckBox;
	import flash.events.SecurityErrorEvent;
	import game.GlobalVariables;
	/**
	 * ...
	 * @author Bamboo
	 */
	public class MainGame extends MovieClip
	{
		//public var menuMain:GameMenuPanel;
		public var userTf:TextField;
		public var usernameTf:TextField;
		//3bac
		public var txtBalanceTf:TextField;
		public var balanceTf:TextField;
		public var messagePopup:MessagePopup;
		public var gameFirst:MovieClip;
		public var gameSecond:MovieClip;
		public var gameThird:MovieClip;
		public var gameName:String = "baccarat.swf";
		public var loadGameFirst:LoadMc;
		public var loadGameSecond:LoadMc;
		public var loadGameThird:LoadMc;
		//public var wtf:TextField;// debug
		public var autoBetting:CheckBox;		
		
		private var listGame3Bac:Array ;
		private var indexGame:int = 0;
		private var gameLocalconnection:GameLocalConnection;
		private var timeLoadGame:String;
		private static const loadCompletedSWF:String = "loadCompletedSWF";
		private static const statusFree:String = "free";
		private static const statusOpened:String = "opened";
		private static const activeRoom:String = "1";
		private static const noneAtiveRoom:String = "0";
		private static const fms:String = "fms";
		//private static const idTables:String = "1,2,4,5,6,7,9,12,13,14,15,16";
		//private static const nameTables:String = "bac,dt,bac,sd,die,bac,ro,bac,bac,bac,bac,bac";
		public var activeRoomOver:int = -1;
		public var channelInfo:ChannelInfo;
		public var channelPanel:ChannelPanel;
		public var iconChannel:MovieClip;
	
		public var txtLobby:TextField;
		public var btnLobby:SimpleButton;
		
		public var currency_mc:MovieClip;
		
		public var soundIcon:MovieClip;
		public var soundList:SoundList;
		public var snd:SoundController;		
		public var volumeGame:VolumeController;
		public var iconVolumeGame:MovieClip;
		
		public function MainGame()	{
			initStatusElement();
			//set status for tables
			//initStatusTables(MainGame.idTables, MainGame.nameTables);
			//init autobet
			initAutoBetting();
			initEvent();
			
			this.soundIcon.gotoAndStop("stop");
			//this.wtf.visible = false;						
		}
		
		private function initStatusElement():void {
			this.loadGameFirst = new LoadMc();
			this.loadGameSecond = new LoadMc();
			this.loadGameThird = new LoadMc();
			this.snd = new SoundController();	
			this.listGame3Bac = new Array();	
			this.soundList.visible = false;			
			this.soundIcon.buttonMode = true;
			this.iconVolumeGame.enabled = false;
			//this.menuMain.visible = false;			
			this.balanceTf.mouseEnabled = false;
			this.channelPanel.visible = false;
			this.iconChannel.enabled = false;
			this.volumeGame.visible = false;
			this.txtLobby.mouseEnabled = false;
			this.btnLobby.useHandCursor = true;
			this.gameLocalconnection = new GameLocalConnection();
		}
		
		private function initEvent():void {
			//debug
			
			//getListGame(GlobalVariables.listGameOpen);
			/*loadListGameValue("1,4,7@open,open,open");	
			getListGameOpenDefault();
			loadGame();
			initFmsMonitor(GlobalVariables.fmsMonitor);//test channel*/
			
			//end debug
			//////////////run web			
			readFlashVar();
			this.loaderInfo.addEventListener(Event.INIT, hdlInitLC);
			this.gameLocalconnection.addEventListener(EventData.LOAD_GAME, hdlLoadGame);
			this.addEventListener(EventData.UPDATE_STATUS_ROOM_OPENED, hdlStatusRoom);
			this.addEventListener(EventData.UPDATE_STATUS_ROOM_FREE, hdlStatusRoom);
			//this.gameLocalconnection.addEventListener(EventData.UPDATE_STATUS_GAME, hdlLocalconnection);
			this.gameLocalconnection.addEventListener(EventData.CLOSE_GAME, hdlLocalconnection);	
			//end run web
			
			//Right Click
			//ExternalInterface.addCallback("openRightClick", openRightClick);
			//End 
			//ExternalInterface.addCallback("sendCloseGame", hdlSendCloseGame);
			this.addEventListener(EventData.BETPLACE_MOUSEOVER_SEND, hdlBetPlaceMouseOverSend);
			this.addEventListener(EventData.BETPLACE_MOUSEOUT, hdlBetPlaceMouseOut);
			this.addEventListener(EventData.UPDATE_VIDEO, hdlUpdateFmsChannel);
			this.addEventListener(EventData.CHIP_ACTIVE, hdlChipActive);
			this.addEventListener(EventData.CHIP_NAVIGATION, hdlChipNavigation);
			this.addEventListener(EventData.UPDATE_SOUNDBACKGROUND, hdlUpdateSoundBackground);
			this.btnLobby.addEventListener(MouseEvent.CLICK, lobbyHandler);
			this.addEventListener(EventData.SEND_BALANCE_TO_MAIN, hdlUpdateBalance);
			this.loadGameFirst.addEventListener(EventData.LOAD_MOVIE, hdlLoadMovie);
			//init channel
			this.iconChannel.addEventListener(MouseEvent.ROLL_OVER, hdlShowChannel);
			this.channelPanel.addEventListener(MouseEvent.ROLL_OUT,	hdlShowChannel);				
			this.soundIcon.addEventListener(MouseEvent.ROLL_OVER, hdlSoundRollOver);
			this.soundIcon.addEventListener(MouseEvent.CLICK, hdlSoundClick);
			this.soundList.addEventListener(MouseEvent.ROLL_OUT, hdlSoundRollOut);
			this.soundList.addEventListener(EventData.UPDATE_SOUNDVOLUMEBACKGROUND, hdlUpdateSoundVolumnBackground);
			this.iconVolumeGame.addEventListener(MouseEvent.ROLL_OVER, hdlShowVolumeGame);
			this.volumeGame.addEventListener(MouseEvent.ROLL_OUT, hdlShowVolumeGame);
			this.iconVolumeGame.addEventListener(MouseEvent.CLICK, hdlVolumeGameClick);
			this.volumeGame.addEventListener(EventData.UPDATE_VOLUMEBACKGROUND, hdlUpdateVolumeBg);
			
			this.addEventListener(EventData.INVALID_TOKEN, hdlInvalidToken);
		}
		
		private function hdlInvalidToken(e:EventData):void {			
			//this.wtf.text = "goi invalidtoken cho main" + " TokenFail" + GlobalVariables.getDate +  " TokenText" + "info"; 
			trace("hdlInvalidToken");
			closeGame();
			this.gameLocalconnection.sendTokenInvalid();							
		}
		
		private function hdlUpdateVolumeBg(e:EventData):void 
		{
			var temp:Number = Number(e.newBalance);
			//snd.setVolumnSound(temp);
			GlobalVariables.volumeSounGame = temp;
			this.loadGameFirst.movieChild.updateVolumeGame();
			this.loadGameSecond.movieChild.updateVolumeGame();
			this.loadGameThird.movieChild.updateVolumeGame();
		}
		
		private function hdlShowVolumeGame(e:MouseEvent):void {
			if ((e.currentTarget == this.iconVolumeGame) && (!this.volumeGame.visible) &&(this.iconVolumeGame.enabled))
			{
				this.soundList.visible = false;
				this.channelPanel.visible = false;
				this.volumeGame.visible = true;
			}
			else if (e.currentTarget == this.volumeGame && this.volumeGame.visible == true)
				this.volumeGame.visible = false;
		}
		
		private function hdlVolumeGameClick(e:MouseEvent):void {
			if (this.iconVolumeGame.enabled)
			{
				//trace("sao vo hay vay ta" + this.iconVolumeGame.enabled);
				if (this.iconVolumeGame.currentLabel == "play") {
					this.iconVolumeGame.gotoAndStop("stop");	
					this.loadGameFirst.movieChild.lockVolumeGame();
					this.loadGameSecond.movieChild.lockVolumeGame();
					this.loadGameThird.movieChild.lockVolumeGame();
				} else {
					this.iconVolumeGame.gotoAndStop("play");		
					this.loadGameFirst.movieChild.unClockVolumeGame();
					this.loadGameSecond.movieChild.unClockVolumeGame();
					this.loadGameThird.movieChild.unClockVolumeGame();
				}
			}
		}
		
		private function hdlUpdateSoundVolumnBackground(e:EventData):void {			
			var temp:Number = Number(e.newBalance);
			snd.setVolumnSound(temp);
			GlobalVariables.volumeSoundBackground = temp;
		}
		/*
		private function initStatusTables(id:String, name:String):void
		{
			var tempId:Array = id.split(",");
			var tempName:Array = name.split(",");
			for (var i:int = 0; i < tempId.length; i++) {
				var tmpObj:Object = new Object();
				tmpObj = { tableId:tempId[i], typeGame:tempName[i], gameStatus:MainGame.statusFree, active:MainGame.noneAtiveRoom };
				GlobalVariables.listGame.push(tmpObj);
			}
				
		}
		*/
		private function hdlSoundClick(e:MouseEvent):void {
			if (this.soundIcon.currentLabel == "play") {
				this.soundIcon.gotoAndStop("stop");
				this.soundList.visible = false;
				snd.stopSound();
			} else {
				this.soundIcon.gotoAndStop("play");				
				snd.playMusic(GlobalVariables.soundActive);					
			}
		}
		
		private function hdlUpdateSoundBackground(e:EventData):void {
			if(this.soundIcon.currentLabel == "stop") {
				this.soundIcon.gotoAndStop("play");
			}
			snd.playMusic(GlobalVariables.soundActive);
		}
		
		private function hdlSoundRollOut(e:MouseEvent):void {
			this.soundList.visible = false;
		}
		
		private function hdlSoundRollOver(e:MouseEvent):void {
			this.channelPanel.visible = false;
			this.volumeGame.visible = false;
			this.soundList.visible = true;
		}
		
		private function hdlShowChannel(e:Event):void 
		{
			if ((e.currentTarget == this.iconChannel) && (!this.channelPanel.visible)&&(this.iconChannel.enabled))
			{
				this.soundList.visible = false;
				this.volumeGame.visible = false;
				this.channelPanel.visible = true;
			}
			else if (e.currentTarget == this.channelPanel && (this.channelPanel.visible))
				this.channelPanel.visible = false;
		}
		
		private function hdlUpdateFmsChannel(e:Event):void 
		{
			getVideoAllChild();
		}
		
		private function lobbyHandler(e:MouseEvent):void {
		   closeGame();
		}
		private function closeGame():void {		
			ExternalInterface.call("CloseBrowser");	
			trace("closeGame");
			try{
				/*this.loadGameFirst.movieChild.closeConnect();
				this.loadGameSecond.movieChild.closeConnect();
				this.loadGameThird.movieChild.closeConnect();
				
				this.removeChild(gameFirst);
				this.removeChild(gameSecond);
				this.removeChild(gameThird);				
				
				gameFirst = null;
				gameSecond = null;
				gameThird = null;			
				
				this.snd.stopSound();				*/	
				this.loadGameFirst.unloadSwf();
				this.loadGameSecond.unloadSwf();
				this.loadGameThird.unloadSwf();
			}catch(e:Error){ }
		}
		
		/*private function hdlSendCloseGame():void
		{
			for (var j:int = 0; j < GlobalVariables.listGame.length; j++ )
			{
				if (GlobalVariables.listGame[j].active == MainGame.activeRoom)
				{	
					this.gameLocalconnection.sendStatusRoom(GlobalVariables.listGame[j].tableId, MainGame.statusFree);
				}
			}
							
		}*/
		
		private function initAutoBetting():void {
			var myformat:TextFormat = new TextFormat();
			myformat.color = 0xFFFFFF;
			myformat.font = "Tahoma";
			myformat.size = 14;

			this.autoBetting.setStyle("textFormat", myformat);
			this.autoBetting.addEventListener(MouseEvent.CLICK, autoBettingHdl);
		}
		
		private function autoBettingHdl(e:Event):void 
		{
			if (e.target.selected)
			{	
				GlobalVariables.autoAcceptBetting = "1";
			}else{
				GlobalVariables.autoAcceptBetting = "0";
			}
			//trace("aaa:"+GlobalVariables.autoAcceptBetting);
		}
			

		private function hdlChipActive(e:EventData):void {			
			this.loadGameFirst.movieChild.setChipActive(e.chipActive);
			this.loadGameSecond.movieChild.setChipActive(e.chipActive);
			this.loadGameThird.movieChild.setChipActive(e.chipActive);
		}
		
		private function hdlChipNavigation(e:EventData):void {			
			this.loadGameFirst.movieChild.setChipNavPos(e.chipPos);
			this.loadGameSecond.movieChild.setChipNavPos(e.chipPos);
			this.loadGameThird.movieChild.setChipNavPos(e.chipPos);
		}
		
		private function openRightClick():void {		
			if (activeRoomOver == 0) {
				this.loadGameFirst.movieChild.rightClick();
			} else if (activeRoomOver == 1) {
				this.loadGameSecond.movieChild.rightClick();
			} else if (activeRoomOver == 2) {
				this.loadGameThird.movieChild.rightClick();
			}
			
		}
		
		private function hdlBetPlaceMouseOut(e:EventData):void {
			activeRoomOver = -1;
		}
		
		private function hdlBetPlaceMouseOverSend(e:EventData):void {			
			for (var i:int = 0; i < this.listGame3Bac.length; i++) {
				if (listGame3Bac[i] == e.chooseRoomBac) {
					//this.wtf.text = "Active Room: " + i;
					activeRoomOver = i;
					break;
				}
			}
		}	
		
		private function hdlLoadMovie(e:EventData):void {
			/*var tem:String = ": " + this.wtf.text;
			this.wtf.text =  e.ms + tem;
			trace("k voooooooooooo" + e.ms + tem);*/
		}
		
		
		private function hdlInitLC(e:Event):void 
		{
			setTimeout(initLC, 100);
		}
		
		private function initLC():void {
			this.gameLocalconnection.init("fromMain" + this.timeLoadGame, "fromGameDetail" + this.timeLoadGame);
			this.gameLocalconnection.sendInfoLoadComplete(GlobalVariables.getDate);
			
			/*var tem:String = ": " + this.wtf.text;
			this.wtf.text =  "initLC" + tem + GlobalVariables.getDate;*/
		}
			
		private function hdlUpdateBalance(e:EventData):void 
		{			
			this.balanceTf.text = Utility.currency(e.newBalance, 2, "");		
			
			//this.wtf.text = this.balanceTf.text;
		}
		
		private function hdlStatusRoom(e:EventData):void 
		{
			var temp:int = -1;
			for (var i:int = 0; i < GlobalVariables.listGame.length; i++ )
			{
				if (GlobalVariables.listGame[i].tableId == e.activeRoomBac)
				{
					temp = i;
					break;
				}	
			}
			if(e.type == EventData.UPDATE_STATUS_ROOM_FREE)
			{	
				GlobalVariables.listGame[temp].gameStatus = MainGame.statusFree;
				GlobalVariables.listGame[temp].active = MainGame.noneAtiveRoom;
				//this.gameLocalconnection.sendStatusRoom(e.activeRoomBac, MainGame.statusFree);
			}
			else if (e.type == EventData.UPDATE_STATUS_ROOM_OPENED)
			{	
				
				GlobalVariables.listGame[temp].gameStatus = MainGame.statusOpened;
				GlobalVariables.listGame[temp].active = MainGame.activeRoom;
				//this.gameLocalconnection.sendStatusRoom(e.activeRoomBac, MainGame.statusOpened);				
			}
		}
		
		private function hdlLoadGame(e:Event):void {
			/*var tem:String = ": " + this.wtf.text;
			this.wtf.text = "hdlLoadGame" + tem + GlobalVariables.getDate;*/
			loadGame();
			//test MONITOR
			//wtf.text = "111" + GlobalVariables.fmsMonitor;			
			initFmsMonitor(GlobalVariables.fmsMonitor);//run web					
		}
		
		
		private function loadGame():void {
			try{
				if (this.listGame3Bac.length > 0 && indexGame < listGame3Bac.length)
				{
					
					GlobalVariables.roomId = listGame3Bac[indexGame];
					//this.wtf.appendText("load game: " + GlobalVariables.roomId);
					switch(indexGame) {
						case 0:
							this.loadGameFirst.loadSwf(gameName, gameFirst);
							this.loadGameFirst.myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, hdlCompleteSWF);
							
							break;
						case 1:
							this.loadGameSecond.loadSwf(gameName, gameSecond);
							this.loadGameSecond.myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, hdlCompleteSWF);
							break;
						case 2:
							this.loadGameThird.loadSwf(gameName, gameThird);
							this.loadGameThird.myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, hdlCompleteSWF);
							break;
					}
					indexGame++;
					trace("loadGame");
				}
			}catch(e:Error){ trace(e.errorID)}
		}
		
			
		private function hdlCompleteSWF(e:Event):void 
		{
			//trace("hdlCompleteSWF");
			sendInfoToGame(MainGame.loadCompletedSWF);
			loadGame();
			setText();
		}
		
		public function showMessage(msg:String) {
			//messagePopup.showMessage(msg);
			//trace("vo day nha");
		}
		
		/**
		 * initUserInfo is contructor after connect to fms successfully
		 * @param	username is GlobalVariables.userName 
		 */
		public function initUserInfo(username:String):void {
			usernameTf.text = username;
		}
		
		public function initCurrency(currency:String):void {			
			switch(currency) {
				case "USD":
					this.currency_mc.gotoAndStop("USD");
					break;
				
				case "SGD":
					this.currency_mc.gotoAndStop("SGD");
					break;
					
				case "HKD":
					this.currency_mc.gotoAndStop("HKD");
					break;
				
				case "TWD":
					this.currency_mc.gotoAndStop("TWD");
					break;
					
				case "CAD":
					this.currency_mc.gotoAndStop("CAD");
					break;			
					
				case "PHP":
					this.currency_mc.gotoAndStop("PHP");
					break;
				
				case "KRW":
					this.currency_mc.gotoAndStop("KRW");
					break;
					
				case "THB":
					this.currency_mc.gotoAndStop("THB");
					break;
				
				case "CNY":
					this.currency_mc.gotoAndStop("CNY");
					break;
					
				case "MYR":
					this.currency_mc.gotoAndStop("MYR");
					break;
				
				case "EUR":
					this.currency_mc.gotoAndStop("EUR");
					break;
					
				case "PTS":
					this.currency_mc.gotoAndStop("USD");
					break;
				
				case "JPY":
					this.currency_mc.gotoAndStop("JPY");
					break;
					
				case "IDR":
					this.currency_mc.gotoAndStop("IDR");
					break;
				
				case "GBP":
					this.currency_mc.gotoAndStop("GBP");
					break;
					
				default:
					this.currency_mc.gotoAndStop("defaultCur");
					break;
			}
		}
		
		/**
		 * @author Bamboo
		 * @param	e
		 */
		public function sendInfoToGame(nameObj:String):void{			
			try{
				if (nameObj == MainGame.loadCompletedSWF)
				{
					if(this.indexGame == 1)
						this.loadGameFirst.movieChild.receiverInfoFromMainGame(nameObj);
					else if(this.indexGame == 2)
						this.loadGameSecond.movieChild.receiverInfoFromMainGame(nameObj);
					else if(this.indexGame == 3)
						this.loadGameThird.movieChild.receiverInfoFromMainGame(nameObj);
				}else
					this.loadGameFirst.movieChild.receiverInfoFromMainGame(nameObj);
			
			}catch (e:Error) {}
		}
		/**
		 * @author Bamboo
		 * @param	e
		 */
		public function receiverInfoFromMenu(nameObj:String):void
		{			
			sendInfoToGame(nameObj);
			
		}
		private function getListGame(listG:String):void {
			this.listGame3Bac = new Array();
			this.listGame3Bac = listG.split(",");
			//trace(this.listGame3Bac);
		}
		private function readFlashVar():void {
			try{
			var paramObj:Object = LoaderInfo(root.loaderInfo).parameters;
			if(paramObj["rtmp"]!=null)
				GlobalVariables.rtmpStr = paramObj["rtmp"];
			if(paramObj["VodRtmp"]!=null)
				GlobalVariables.vodRtmp = paramObj["VodRtmp"];
			if(paramObj["VPN"]!=null)
				GlobalVariables.vpn = paramObj["VPN"];
			if(paramObj["MaxRo"]!=null)
				GlobalVariables.maxRo = paramObj["MaxRo"];
			if(paramObj["_getDate"]!=null)
				GlobalVariables.getDate = paramObj["_getDate"];
			if(paramObj["gameCard"]!=null)
				GlobalVariables.gameCard = paramObj["gameCard"];
			if(paramObj["ip"]!=null)
				GlobalVariables.ip = paramObj["ip"];
			if(paramObj["countrycode"]!=null)
				GlobalVariables.countryCode = paramObj["countrycode"];
			
			//GlobalVariables.listGameOpen = paramObj["listGame"];				
			loadListGameValue(paramObj["listGame"]);				
			
			//getListGame(GlobalVariables.listGameOpen);
			getListGameOpenDefault();
			
			/*this.wtf.appendText("rtmp: " + GlobalVariables.rtmpStr + " @ vodRtmp: " + GlobalVariables.vodRtmp + 
								" @ vpn: " + GlobalVariables.vpn + " @ maxRo: " + GlobalVariables.maxRo +
								" @ getDate: " + GlobalVariables.getDate + " @ ip: " + GlobalVariables.ip +
								" @ listGame: " + GlobalVariables.listGameOpen);*/
			
			this.timeLoadGame = GlobalVariables.getDate;
			ExternalInterface.call("alertScript", "readFlashVar")
			}catch(e:Error){}
		}
		
		private function hdlLocalconnection(e:Event) {
			/*if(e.type == EventData.UPDATE_STATUS_GAME)
			{	var temp:Array = GlobalVariables.listStatusGame.split(",");
				for (var i:int = 0; i < GlobalVariables.listGame.length; i++ )
					GlobalVariables.listGame[i].gameStatus = temp[i];
			}else */
			if (e.type == EventData.CLOSE_GAME) {
				
				 closeGame();
			}
			
		}
		/*private function hdlUpdateStatusGame(e:Event) {
			var temp:Array = GlobalVariables.listStatusGame.split(",");
			//this.wtf.text = "aaaaaaaaaaaaa:" + GlobalVariables.listStatusGame;
			for (var i:int = 0; i < GlobalVariables.listGame.length; i++ )
			{
				GlobalVariables.listGame[i].gameStatus = temp[i];
			}
		}*/
		/**
		 * Channel
		 */
		import flash.net.Responder;	
		public var ncChannelTime:NetConnection;
		//public var ncChannelBw:NetConnection;
		private var setCheckConnect:uint;
		
		private function initFmsMonitor(str:String):void {
			trace(str);
			this.channelInfo = new ChannelInfo();
			this.channelInfo.init(str);
			
			this.channelPanel.addListChannel(this.channelInfo.listChannel);
			checkTime(this.channelInfo.listChannel[this.channelInfo.countCheckFms][MainGame.fms]);
		}
		
			
		/*private function checkBw(rtmpStr:String):void {
			trace("checkBw:" + rtmpStr);
			
			ncChannelBw = new NetConnection();
			ncChannelBw.client = this;
			ncChannelBw.addEventListener(NetStatusEvent.NET_STATUS, netStatusBwHdl);
			ncChannelBw.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHdl);
			var rtmp:String = rtmpStr.substr(0, rtmpStr.length - 4);
			rtmp = rtmp + "bandwidth";
			//trace("rtmp:" + rtmp);
			ncChannelBw.connect(rtmp);
			
			setCheckConnect = setTimeout(closeCheckBw, 4000);
			
		}
		private function closeCheckBw():void {
			ncChannelBw.close();
			this.channelInfo.countCheckFms++;
			if (this.channelInfo.countCheckFms < this.channelInfo.listTimeChannel .length) {
				checkBw(this.channelInfo.listChannel[this.channelInfo.countCheckFms][MainGame.fms]);
			}else {
				reChooseChannel();
			}
		}
		
		private function netStatusBwHdl(e:NetStatusEvent):void 
		{
			var event:EventData;
			switch(e.info.code) {
				case "NetConnection.Connect.Success":
					ncChannelBw.call("checkBandwidth", new Responder(successCallFMS, failCallFMS));
					clearTimeout(setCheckConnect);
					
					break;
				case "NetConnection.Connect.Failed":
					break;
				case "NetConnection.Connect.Rejected":
					break;
				case "NetConnection.Connect.Closed":				
					break;
			}
			
		}
		
		private function reChooseChannel():void
		{
			if (this.channelInfo.listBwChannel.length > 0) {
				//update fms to load video LISTBWCHANNEL
				//load video, update UI channel
				activeVideoChannel(this.channelInfo.listBwChannel[this.channelInfo.listBwChannel.length - 1][MainGame.fms]);
			}
			else {
				//update fms to load video LISTCHANNEL
				//load video, update UI channel
				activeVideoChannel(this.channelInfo.listChannel[0][MainGame.fms]);
			}
		}*/
		private var connectCheckTime:Object = new Object();
		private function checkTime(rtmp:String)
		{
			
			ncChannelTime = new NetConnection();	
			ncChannelTime.client = connectCheckTime;
			//connectCheckTime["onBWDone"] = onBWDone;
			ncChannelTime.addEventListener(NetStatusEvent.NET_STATUS, netStatusTimeHdl);
			ncChannelTime.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHdl);
			ncChannelTime.connect(rtmp);
			this.channelInfo.lastTimeConnect = this.channelInfo.getTimeCurrent();
			setCheckConnect = setTimeout(closeCheckTime, 1000); 
		}	
		/**
		 * close checkTime if Responder >1000
		 */
		private function closeCheckTime():void {
			ncChannelTime.close();
			ncChannelTime = null;
			trace("closeCheckTime" + this.channelInfo.countCheckFms +"fail");
			this.channelInfo.countCheckFms++;
			if (this.channelInfo.countCheckFms < this.channelInfo.listChannel.length) {
				checkTime(this.channelInfo.listChannel[this.channelInfo.countCheckFms][MainGame.fms]);
			}else {
				if (this.channelInfo.listTimeChannel.length == 0)
					this.channelInfo.listTimeChannel = this.channelInfo.randomArray(this.channelInfo.listChannel);	
				//this.channelInfo.countCheckFms = 0;
				//checkBw(channelInfo.listTimeChannel[this.channelInfo.countCheckFms][MainGame.fms]);//not check BW
				activeVideoChannel(this.channelInfo.listTimeChannel[0][MainGame.fms]);// check time and do only
				
			}
		}
		
		
		private function netStatusTimeHdl(e:NetStatusEvent):void {		
			var event:EventData;
			trace("netStatusNcIdHdl:" + e.info.code);
			ncChannelTime.close();
			ncChannelTime = null;
			switch(e.info.code) {
				case "NetConnection.Connect.Success":
					clearTimeout(setCheckConnect);
					this.channelInfo.getTimeSuccess();
					if (this.channelInfo.countCheckFms < this.channelInfo.listChannel.length) {
						
						checkTime(this.channelInfo.listChannel[this.channelInfo.countCheckFms][MainGame.fms]);
						
					}else
					{	// done checkTime and had fms that connected by time < 1000
						//this.channelInfo.countCheckFms = 0;
						//checkBw(channelInfo.listTimeChannel[this.channelInfo.countCheckFms][MainGame.fms]);
						activeVideoChannel(this.channelInfo.listTimeChannel[0][MainGame.fms]);// check time and do only
					}
					break;
				case "NetConnection.Connect.Failed":
					break;
				case "NetConnection.Connect.Rejected":
					break;
				case "NetConnection.Connect.Closed":
					break;
			}
			

		}
		
		private function securityErrorHdl(e:SecurityErrorEvent):void {
			//trace("SecurityErrorHdl: " + e);
		}
		public function successCallFMS(strMsg:String):void {
			//trace("successCallFMS");
		}
		
		
		public function failCallFMS(strMsg:String):void {
			//trace("failCallFMS");
		}
		
		
		
		
	
		/*public function onBWDone(...rest):void {
			if(rest.length != 0){
				var temp:int = int(rest[0]);
				if (temp > 250) {
					//update fms to load video LISTTIMECHANNEL
					//load video, update UI channel
					activeVideoChannel(this.channelInfo.listTimeChannel[this.channelInfo.countCheckFms][MainGame.fms]);
				}else {
					this.channelInfo.getBwSuccess(rest[0]);
					if (this.channelInfo.countCheckFms < this.channelInfo.listTimeChannel.length)
						checkBw(channelInfo.listTimeChannel[this.channelInfo.countCheckFms][MainGame.fms]);
					else
						reChooseChannel();
				}
				
			}
			ncChannelBw.close();
		}*/
		//End channel
		private function getVideoAllChild():void {			
			this.loadGameFirst.movieChild.updateVideoPath(GlobalVariables.fmsChannel);
			this.loadGameSecond.movieChild.updateVideoPath(GlobalVariables.fmsChannel);
			this.loadGameThird.movieChild.updateVideoPath(GlobalVariables.fmsChannel);
			ncChannelTime.close();
			ncChannelTime = null;
		}
		
		private function activeVideoChannel(nameFmsChannel:String) {
			trace("activeVideoChannel:" + nameFmsChannel);
			GlobalVariables.fmsChannel = nameFmsChannel;
			//set color for channel active and active iconChannel
			this.channelPanel.setChannelActiving(nameFmsChannel, 0xFFCC32);
			this.channelPanel.updateChannelActiving(nameFmsChannel);
			this.iconChannel.enabled = true;
			this.iconChannel.buttonMode = true;
			this.iconVolumeGame.enabled = true;
			this.iconVolumeGame.buttonMode = true;
		
			getVideoAllChild();
			
		}
		
		/**
		 * @author Daisy
		 */
		private function getListGameOpenDefault():void {
			this.listGame3Bac = new Array();
			for (var i = 0; i < GlobalVariables.arrListGameBacTable.length; i ++) {
				if (GlobalVariables.arrListGameBacStatus[i] == 0) {
					this.listGame3Bac.push(GlobalVariables.arrListGameBacTable[i]);
					GlobalVariables.arrListGameBacStatus[i] = 1;
					//wtf.appendText("Table: " + GlobalVariables.arrListGameBacTable[i]);
				}
				if (this.listGame3Bac.length == 3) {					
					break;
				}
			}
		}
		
		/**
		 * @author Daisy
		 * @param	str
		 */
		private function loadListGameValue(str:String) {
			var arr:Array = new Array();			
			arr = str.split("@");
			GlobalVariables.arrListGameBacTable = new Array();
			GlobalVariables.arrListGameBacStatus = new Array();
			
			GlobalVariables.arrListGameBacTable = String(arr[0]).split(",");
			
			var arrStatus:Array = new Array();
			arrStatus = String(arr[1]).split(",");
			
			for (var i:int = 0; i < arrStatus.length; i ++ ) {
				if (arrStatus[i] == "open") {
					GlobalVariables.arrListGameBacStatus.push(0);
				}else {
					GlobalVariables.arrListGameBacStatus.push(-1);
				}
			}					
		}
		
		private function setText():void {			
			this.userTf.text = GlobalVariables.langInfo.hashTable.lookupString("MNwelcome");
			this.txtBalanceTf.text = GlobalVariables.langInfo.hashTable.lookupString("MNbalance");
			this.txtLobby.text = GlobalVariables.langInfo.hashTable.lookupString("MNLobby");
			this.autoBetting.label = GlobalVariables.langInfo.hashTable.lookupString("autoConfirm");
		}
	}
}